package Scuttlebutt;

import java.awt.event.*;
import javax.swing.*;
import java.awt.Container;
import java.awt.Insets;
import java.awt.Dimension;
import java.io.*;
import java.lang.Thread;
import glue.ftp.*;

public class SynchronizeThread implements Runnable
{
	SynchronizeDlg.SynchronizePanel observer = null;
	SynchronizeDlg dlg = null;
	Scuttlebutt parent = null;

	public SynchronizeThread(Scuttlebutt parent, SynchronizeDlg dlg)
	{
		this.parent = parent;
		this.dlg = dlg;
		this.observer = dlg.syncp;
        try
        {
    	    parent.getFTP().ftpConnect(parent.getProject().getFTPaddress(), parent.getProject().getUsername(), parent.getProject().getPassword());
    	    parent.setRemoteHomeDirectory(parent.getFTP().getDirectory());
        }catch(Exception e){
			String msg = new String("failed to connect:" + e);
 		   	JOptionPane.showMessageDialog(null, msg, "Error", JOptionPane.ERROR_MESSAGE);
           	System.err.println(msg);
        }
	}
	public void run(){
		try{		
			FolderNode node = (FolderNode)parent.getRootNode();
			node.setRemoteDirectory(parent.getRemoteHomeDirectory());
			parent.getFTP().setDirectory(parent.getRemoteHomeDirectory());
			int count = 0;
			count = getDirectories(count);
			getFiles(count);
			parent.getButtonBar().getConnectButton().setEnabled(true);
			dlg.setVisible(false);
	    } catch(IOException e){
	        System.err.println("Synchronize failed IOException:" + e.getMessage());
	    }catch(FtpException e){
	        System.err.println("Synchronize failed FtpException:" + e.getMessage());
	    }
	}

	private int getDirectories(int count){
		try{
			FtpListResult result = parent.getFTP().getDirectoryContent();
	        while(result.next()){
	            int test = result.getType();
	            if(test == FtpListResult.DIRECTORY){
		            if(dlg.sp.getSelected(count).booleanValue()){
						FolderNode o = (FolderNode)parent.getRootNode();
						FolderNode node = o.addDirectory(parent, result.getName());
						parent.getFTP().setDirectory(new String(parent.getRemoteHomeDirectory() + result.getName()));
						observer.SetText("Creating folder: " + parent.getFTP().getDirectory());

						SearchDirectory(parent.getFTP().getDirectory(), "", node);
						parent.getFTP().setDirectory(parent.getRemoteHomeDirectory());
		            }
					count++;
	            }
	            
	        }
	    } catch(Exception e){
//	        System.err.println("num:" + num + " *Thread error:" + e);
	    }
	    
	    return count;
	}
	
	private void getFiles(int count){
		try{
//			parent.getFTP().setDirectory(parent.getRemoteHomeDirectory());
			FtpListResult result = parent.getFTP().getDirectoryContent();
	        while(result.next()){
	            int test = result.getType();
	            if(test == FtpListResult.FILE){
		            if(dlg.sp.getSelected(count).booleanValue()){
						FolderNode o = (FolderNode)parent.getRootNode();
						downloadFile(parent.getFTP().getDirectory(), "", result.getName(), (int)result.getSize(), o);
		            }
					count++;
	            }
	            
	        }
	    } catch(Exception e){
//	        System.err.println("num:" + num + " *Thread error:" + e);
	    }
	    
	}

/*	do not delete
	public void run(){
		try{			
			FolderNode node = (FolderNode)parent.getRootNode();
			node.setRemoteDirectory(parent.getRemoteHomeDirectory());
			parent.getFTP().setDirectory(parent.getRemoteHomeDirectory());
			SearchDirectory(parent.getFTP().getDirectory(), "", node);
			observer.setVisible(false);
			parent.getButtonBar().getConnectButton().setEnabled(true);
	    } catch(IOException e){
	        System.err.println("Synchronize failed IOException:" + e.getMessage());
	    }catch(FtpException e){
	        System.err.println("Synchronize failed FtpException:" + e.getMessage());
	    }
	}
*/	
  	public void SearchDirectory(String start_dir, String path, FolderNode root){
		String newStartDirectory = null;
		try{
			if(path.length() == 0){
				newStartDirectory = new String(start_dir);
			}else{
				newStartDirectory = new String(start_dir + path);
			}
			
//			System.out.println("newStartDirectory:" + newStartDirectory);
			parent.getFTP().setDirectory(newStartDirectory);
			
			FtpListResult result = parent.getFTP().getDirectoryContent();
	        while(result.next())
	        {
	            int type = result.getType();
	            if(type == FtpListResult.DIRECTORY){
		            
//		            System.out.println("path:" + path + " Name:" + result.getName());
		            
		            String a = null;
					if(path.length() == 0){
						a = new String( result.getName());
					}else{
						a = new String(path + File.separatorChar + result.getName());
					}
					
//					a = new String((path.length() == 0)?new String(newStartDirectory + result.getName()):new String(path + File.separatorChar + result.getName()));
					
					
					
					File dir = new File(parent.getProject().getProjectPath().toString() + File.separatorChar + parent.getProject().getProjectTitle() + File.separatorChar + newStartDirectory + File.separatorChar + a);
		            dir.mkdir();
		            
		            FolderNode node = root.addDirectory(parent, result.getName());
		            
		          /*FolderNode node = new FolderNode(result.getName(), dir.getPath());		            
		            node.setRemoteDirectory(path);
		            root.addSortable(node);
		            observer.SetText("Created folder: " + newStartDirectory + result.getName());
		            */
		            String p = null;
		            if(path.length() == 0){
		            	p = node.toString();
		            }else{
			            p = path + File.separatorChar + node.toString();
		            }
		            

		            SearchDirectory(start_dir, p, node);
		            
	            }else if(type == FtpListResult.FILE){
		            downloadFile(newStartDirectory, path, result.getName(), (int)result.getSize(), root);

	            
				}else if(type == FtpListResult.LINK){
//	                System.out.print("LINK\t");
	            }else if(type == FtpListResult.OTHERS){
//	                System.out.print("OTHER\t");
	            }
	        }
			
	    } catch(Exception e){
//	        System.err.println("num:" + num + " *Thread error:" + e);
	    }
  	}
  	
  	private void downloadFile(String t, String path, String filename, int size, FolderNode root){
		try{
			String new_file = null;
			
			new_file = new String(parent.getProject().getProjectPath().toString() + File.separatorChar + parent.getProject().getProjectTitle() + new String( (path.length() == 0)?t:new String(/*File.separatorChar +*/ t + File.separatorChar)) + filename);
			SortableNode node = new SortableNode(filename, new_file);
			
			observer.num_of_bytes = 0;
			observer.bar.setMinimum(0);
			observer.bar.setValue(0);
				
			observer.bar.setMaximum(size);
			
			parent.getFTP().setDirectory(t);	
	
			int idx = root.find(node.toString());
			if( idx == -1){
				observer.SetText(new String (new String((size > 0)?"Downloading file: " : "Creating file: " ) + t /*+ new String((t.endsWith(String.valueOf(File.separatorChar)))?new String("") : String.valueOf(File.separatorChar))*/ + filename));
				parent.getFTP().getBinaryFile(filename, new_file, observer);
//				node.setUploaded(true);
//				root.addSortable(node);
				File f = new File(new_file);
				root.addFile(parent, f.getName(), true);
			}else{
			}
	    } catch(Exception e){
	    }
  	}
}

